package com.jyniubi.gamll.auth.service.impl;

import com.jyniubi.gamll.auth.config.JwtProperties;
import com.jyniubi.gamll.auth.feign.GmallUmsClient;
import com.jyniubi.gamll.auth.service.AuthService;
import com.jyniubi.gmail.common.bean.ResponseVo;
import com.jyniubi.gmail.common.exception.AuthException;
import com.jyniubi.gmail.common.utils.CookieUtils;
import com.jyniubi.gmail.common.utils.IpUtils;
import com.jyniubi.gmail.common.utils.JwtUtils;
import com.jyniubi.gmail.ums.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@EnableConfigurationProperties(JwtProperties.class)
public class AuthServiceImpl implements AuthService {

    @Autowired
    private GmallUmsClient umsClient;
    @Autowired
    private JwtProperties properties;

    @Override
    public void accredit(String loginName, String password, HttpServletRequest request,
                         HttpServletResponse response) {
        // 1. 调用ums接口查询用户
        ResponseVo<UserEntity> userEntityResponseVo = this.umsClient.queryUser(loginName, password);
        UserEntity userEntity = userEntityResponseVo.getData();
        // 2. 判断用户是否为空，为空则抛出异常
        if (userEntity == null){
            log.error("userEntity:" + userEntity);
            throw new AuthException("用户名或密码错误");
        }
        // 3. 组装载荷
        Map<String, Object> map = new HashMap<>();
        map.put("userId",userEntity.getId());
        map.put("username",userEntity.getUsername());
        // 为防止盗用，把登录用户的ip也封装到载荷中
        map.put("ip",IpUtils.getIpAddressAtService(request));

        try {
            // 生成token
            String token = JwtUtils.generateToken(map, this.properties.getPrivateKey(), this.properties.getExpire());
            // 放入cookie
            CookieUtils.setCookie(request,response,this.properties.getCookieName(),token,this.properties.getExpire() * 60);
            // 为了方便展示，将用户昵称放入cookie
            CookieUtils.setCookie(request,response,this.properties.getUnick(),userEntity.getNickname(),this.properties.getExpire() * 60);
        } catch (Exception e) {
            log.error("生成token异常",e);
        }
    }
}
